package com.hongye.app.controller;

import java.util.List;

import org.apache.log4j.Logger;

import com.hongye.app.model.BuyerStatisticsModel;
import com.hongye.app.model.EvaluationModel;
import com.hongye.app.model.GoodsModel;
import com.hongye.app.model.OrderGoodsModel;
import com.hongye.app.model.OrderInfoModel;
import com.hongye.app.model.ReturnGoodsModel;
import com.hongye.util.AlipayUtils;
import com.hongye.util.PushUtils;
import com.hongye.util.Utils;
import com.hongye.util.WeixinUtils;
/**
 * 定时任务类--每天凌晨3点执行
 * @author Administrator
 *
 */
public class Job implements Runnable{
	private static Logger log = Logger.getLogger(Job.class);
	private static final long TIME_HOUR_1 = 60*60*1000;//订单创建1小时时间长度
	private static final long TIME_DAY_3 = 3*24*60*60*1000;//3天时间长度
	private static final long TIME_DAY_7 = 7*24*60*60*1000;//7天时间长度
	private static final long TIME_DAY_10 = 10*24*60*60*1000; //10天时间长度
	private static final long TIME_DAY_17 = 17*24*60*60*1000; //17天时间长度
	public void run() {
		
		int count1 = 0;	//未付款，被取消的订单条数
		int count2 = 0;	//正常订单已付款条数
		int count3 = 0;	//被延期的订单已付款的条数
		int count4 = 0;	//所有订单交易完成的条数
		int count5 = 0;	//所有买家申请退款完成的条数
		int count6 = 0;	//所有取消买家退货申请的条数
		
		//-----------------------------取消订单创建超过60分钟并且未付款（即订单状态小于2）的订单-------------------------
		List<OrderInfoModel> order_list = OrderInfoModel.dao.cancelOrder();
		if(log.isInfoEnabled()){log.info("--------------扫描取消订单完成：共计："+order_list.size()+"条！-----------------");}
		for(OrderInfoModel order : order_list){
			long time = Utils.getLongTime(order.get("time").toString());
			if(time > TIME_HOUR_1){	//超过1小时
				boolean boo = order.set("order_status", 6).update();//设置状态6为订单被取消
				if(boo){
					List<OrderGoodsModel> ordergoods = OrderGoodsModel.getByOrderId(order.getInt("id"));
					for (OrderGoodsModel orderGoodsModel : ordergoods) {
						GoodsModel.dao.edit_stock_sales(orderGoodsModel.getInt("goods_id"), 1, orderGoodsModel.getInt("goods_num"));//完成后归还库存，减少销量
					}
					PushUtils.MSG_Single(order.getStr("phone"), "A06", "您的订单因长时间未付款，被取消了，请重新下单！");
					if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"设置取消成功！");}
					count1 += 1;
				}else{
					if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"处理异常！");}
				}
			}else{
				continue;
			}
		}
		if(log.isInfoEnabled()){log.info("取消未付款订单完成：共计："+count1+"条！");}
		
		
		//------------------------定时扫描订单，完成规定时间10天确定收货,去评价--------------------------
		List<OrderInfoModel> order_list2 = OrderInfoModel.dao.confirmReceipt();
		if(log.isInfoEnabled()){log.info("---------------扫描完成：共计："+order_list2.size()+"条！------------------");}
		for(OrderInfoModel order : order_list2){
			long time = Utils.getLongTime(order.get("time").toString());
			if(time>TIME_DAY_10){	//正常十天
				boolean boo = order.set("order_status", 5).update();//状态5为订单确定收货
				if(boo){
					BuyerStatisticsModel.Update_Add_Usable(order);
					if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"设置成功！");}
					count2 += 1;
				}else{
					if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"设置出现异常！");}
				}
			}else{
				continue;
			}	
		}
		if(log.isInfoEnabled()){log.info("正常订单确定收货,给商家付款完成：共计："+count2+"条！");}
		
		
		//--------------------------------延长收货订单，七天确定收货，给商家付款-----------------------------------------
		List<OrderInfoModel> order_list3 = OrderInfoModel.dao.delayOrder();
		if(log.isInfoEnabled()){log.info("------------扫描完成：共计："+order_list3.size()+"条！-------------");}
		for(OrderInfoModel order : order_list3){
			long time = Utils.getLongTime(order.get("time").toString());
			if(time>TIME_DAY_17){	//10天延期7天
				boolean boo_alipay = true;
				if(boo_alipay){
					//状态5为订单确定收货
					order.set("order_status", 5).update();
					BuyerStatisticsModel.Update_Add_Usable(order);
				}else{
					if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"支付出现异常！");}
				}
				if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"设置成功！");}
				count3 += 1;
			}else{
				continue;
			}
		}
		if(log.isInfoEnabled()){log.info("延期订单确定收货,给商家付款完成：共计："+count3+"条！");}
		
		
		//--------------------------------扫描确定收货订单，七天评价关闭，交易完成-----------------------------------------
		List<OrderInfoModel> order_list4 = OrderInfoModel.dao.evaluateOrder();
		if(log.isInfoEnabled()){log.info("------------扫描完成：共计："+order_list4.size()+"条！-----------");}
		for(OrderInfoModel order : order_list4){
			long time = Utils.getLongTime(order.get("time").toString());
			if(time>TIME_DAY_7){	
				//状态7为订单完成
				boolean boo = order.set("order_status", 7).set("finish_time", Utils.getDate()).update();
				if(boo){
					//添加默认评论
					EvaluationModel em = new EvaluationModel();
					List<OrderGoodsModel> ogms = OrderGoodsModel.getByOrderId(order.getInt("id"));
					boolean boo2 = em.set("user_id", order.get("user_id")).set("order_id", order.get("id")).set("logistic_level", 5)
								.set("seller_id", ogms.get(0).get("seller_id")).set("goods_level", 5).set("service_level", 5).set("c_time", Utils.getDate()).save();
					if(boo2){
						//买家提交评论后  更新商家信誉度
						boolean boo3 = BuyerStatisticsModel.UpdateSeller_credit(ogms.get(0).getStr("seller_id"));
						if(boo3){
							if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"设置成功！");}
							count4 += 1;
						}else{
							if(log.isInfoEnabled()){log.info("订单--"+ order.get("order_sn")+"处理异常！");}
						}
					}
				}
			}else{
				continue;
			}
		}
		if(log.isInfoEnabled()){log.info("订单交易完成：共计："+count4+"条！");}
//		
		
		//--------------------------------买家提交退款申请，商家3天内不受理，自动默认同意退款-----------------------------------------
		List<ReturnGoodsModel> retrun_list = ReturnGoodsModel.dao.getReturnApplyOrder();
		if(log.isInfoEnabled()){log.info("-------------扫描完成：共计："+retrun_list.size()+"条！-----------");}
		for(ReturnGoodsModel returngoods : retrun_list){
			long time = Utils.getLongTime(returngoods.get("time").toString());
			if(time>TIME_DAY_3){
				OrderInfoModel info = OrderInfoModel.dao.findFirst("select * from order_info where order_sn = '"+returngoods.get("order_sn")+"'");
				ReturnGoodsModel reg = ReturnGoodsModel.dao.findById(returngoods.getInt("return_id"));
				//给买家退钱 如果存在总订单，用总订单号
				OrderInfoModel orderinfo = OrderInfoModel.isTotalOrder(info.get("id"));
				boolean boo_refund = false;
				if(orderinfo != null){
					if("0".equals(orderinfo.get("payment_channel"))){//支付宝
						boo_refund = AlipayUtils.refund(orderinfo.getStr("order_sn"), info.get("total_price"));
					}else if("1".equals(orderinfo.get("payment_channel"))){//微信
						try {
							boo_refund = WeixinUtils.refund(orderinfo.getStr("order_sn"), orderinfo.getFloat("total_price"), info.getFloat("total_price"));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}else{
					if("0".equals(info.get("payment_channel"))){//支付宝
						boo_refund = AlipayUtils.refund(info.getStr("order_sn"), info.get("total_price"));
					}else if("1".equals(info.get("payment_channel"))){//微信
						try {
							boo_refund = WeixinUtils.refund(info.getStr("order_sn"), info.getFloat("total_price"), info.getFloat("total_price"));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				if(boo_refund){
					//完成后归还库存，减少销量
						//订单状态9为订单退款完成
					boolean boo_info = info.set("order_status", 9).set("update_time", Utils.getDate()).update();
					//退货状态8为订单退款完成
					boolean boo_return = reg.set("return_status", 8).set("update_time", Utils.getDate())
							.set("data", ReturnGoodsModel.getData(returngoods, -1, "热播购系统", "商家3天为处理，系统自动退款成功！")).update();
					if(boo_return && boo_info ){
						GoodsModel.dao.edit_stock_sales(returngoods.getInt("g_id"), 1, returngoods.getInt("g_num"));
						BuyerStatisticsModel.Update_Reduce_Disable(info);
						PushUtils.MSG_Single(info.getStr("phone"), "A05", "您的退款进度更新啦！去看看吧！");
						PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(info.getStr("order_sn")), "B04", "您的退款进度更新啦！去看看吧！");
						if(log.isInfoEnabled()){log.info("订单--"+ returngoods.get("order_sn")+"设置成功！");}
						count5 += 1;
					}else{
						if(log.isInfoEnabled()){log.info("订单--"+ returngoods.get("order_sn")+"处理异常！");}
					}
				}else{
					if(log.isInfoEnabled()){log.info("订单--"+ returngoods.get("order_sn")+"退款过程异常！");}
				}
			}else{
				continue;
			}
		}
		if(log.isInfoEnabled()){log.info("卖家三天未同意，给买家退款完成：共计："+count5+"条！");}
		
		
		//--------------------------------商家同意退货申请，买家3天内不发货，自动默认取消退货流程-----------------------------------------
		List<ReturnGoodsModel> retrun_list2 = ReturnGoodsModel.dao.getSellerAgreeReturnOrder();
		if(log.isInfoEnabled()){log.info("--------------扫描完成：共计："+retrun_list2.size()+"条！-------------");}
		for(ReturnGoodsModel returngoods : retrun_list2){
			long time = Utils.getLongTime(returngoods.get("time").toString());
			if(time>TIME_DAY_3){
				String sql_info = "select * from order_info where order_sn = '"+returngoods.get("g_order")+"'";
				OrderInfoModel order = OrderInfoModel.dao.findFirst(sql_info);
				//更新退货表
				boolean boo = returngoods.set("return_status", 3).set("update_time", Utils.getDate()).set("data", ReturnGoodsModel.getData(returngoods, 1, "买家", "商家已撤销退款申请")).update();
				if(boo){
					//继续发货状态3
					boolean boo2 = order.set("order_status", 3).set("update_time", Utils.getDate()).update();
					if(boo2){
						PushUtils.MSG_Single(order.getStr("phone"), "A05", "您的退款进度更新啦！去看看吧！");
						PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(order.getStr("order_sn")), "B04", "您的退款进度更新啦！去看看吧！");
						if(log.isInfoEnabled()){log.info("订单--"+ returngoods.get("order_sn")+"设置成功！");}
						count6 += 1;
					}else{
						if(log.isInfoEnabled()){log.info("订单--"+ returngoods.get("order_sn")+"处理异常！");}
					}
				}
			}else{
				continue;
			}
		}
		if(log.isInfoEnabled()){log.info("买家三天未发货，撤销退款申请已完成：共计："+count6+"条！");}
	}

}
